﻿using DevExpress.XtraCharts;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ExceptionAnaliz
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        DateTime date;
        DateTime dtTime;
        SecondaryAxisY myAxisY;
        DataManager dm;
        private void Form1_Load(object sender, EventArgs e)
        {
            string AppDataPath = CreateAppDataFolder("ConfExpert");
            AppDataPath = AppDataPath + "\\" + "connection.txt";
            FileInfo fi = new FileInfo(AppDataPath);
            if (!fi.Exists)
            {
                XtraMessageBox.Show(AppDataPath + " dosyası yok!");
                return;
            }
            string conString = File.ReadAllText(fi.FullName);
            dm=new DataManager(conString);
            //dateEdit1.Properties.HighlightTodayCell = DevExpress.Utils.DefaultBoolean.True;
            dateEdit1.DateTime = DateTime.Now;
            gridView1.OptionsBehavior.Editable = false;
            gridView2.OptionsBehavior.Editable = false;

            DataSet d = dm.ExecuteDataSet("GetExceptionUsrMsg", dtTime);
            DataTable dtex = d.Tables[0];
            DataTable dtexmessage = d.Tables[1];
            gridView1.BestFitColumns();
            gridView3.BestFitColumns();
            XYDiagram diagram = (XYDiagram)chartControl1.Diagram;
            chartControl1.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True;
            chartControl1.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.RightOutside;
            chartControl1.Legend.VerticalIndent = 8;

            gridView1.EditingValue = false;
            gridView3.EditingValue = false;
            timer1.Interval = 60000;
            btnOnceki.Click += btnOnceki_Click;
            btnSonraki.Click += btnSonraki_Click;
        }

        void btnSonraki_Click(object sender, EventArgs e)
        {
            dateEdit1.DateTime = dateEdit1.DateTime.AddDays(1);
        }

        void btnOnceki_Click(object sender, EventArgs e)
        {
            dateEdit1.DateTime = dateEdit1.DateTime.AddDays(-1);
        }

        private void Bind(DateTime dateEdit, DataManager dm)
        {
            gridView1.FocusedRowHandle = -1;
            chartControl1.Series.Clear();
            myAxisY = new SecondaryAxisY("my Y-Axis");
            myAxisY.NumericScaleOptions.MeasureUnit = NumericMeasureUnit.Ones;
            myAxisY.NumericScaleOptions.GridSpacing = 1;
            myAxisY.NumericScaleOptions.GridAlignment = NumericGridAlignment.Ones;
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Clear();
            ((XYDiagram)chartControl1.Diagram).SecondaryAxesY.Add(myAxisY);
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.Auto = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.WholeRange.SetMinMaxValues(1.50, 22.50);
            ((XYDiagram)chartControl1.Diagram).AxisX.VisualRange.Auto = false;
            ((XYDiagram)chartControl1.Diagram).AxisX.VisualRange.SetMinMaxValues(1.50, 22.50);
            ((XYDiagram)chartControl1.Diagram).AxisX.NumericScaleOptions.GridOffset = 1;
            ((XYDiagram)chartControl1.Diagram).AxisY.NumericScaleOptions.GridAlignment = NumericGridAlignment.Ones;
            ((XYDiagram)chartControl1.Diagram).AxisX.Alignment = AxisAlignment.Zero;
            ((XYDiagram)chartControl1.Diagram).AxisX.VisualRange.AutoSideMargins = true;
            ((XYDiagram)chartControl1.Diagram).AxisX.NumericScaleOptions.GridSpacing = 1;
            var dateselected = dateEdit;
            date = new DateTime(dateEdit.Year, dateEdit.Month, dateEdit.Day, 00, 00, 00);
            DataTable dtr = dm.ExecuteDataTable("GetExceptionByMinute", dateEdit1.DateTime);
            if (dtr.Rows.Count > 0)
            {
                if (dateEdit1.DateTime.Date != DateTime.Now.Date)
                    dtr.Rows.Add(24.00, dtr.Rows[dtr.Rows.Count - 1]["HataSayisi"], 1);
            }
            Series series2 = new Series("Toplam Hata Sayısı", ViewType.Line);
            series2.DataSource = dtr;
            series2.ArgumentScaleType = ScaleType.Numerical;
            series2.ArgumentDataMember = "Dk";
            series2.ValueScaleType = ScaleType.Numerical;
            series2.ValueDataMembers.AddRange(new string[] { "HataSayisi" });
            chartControl1.Series.Add(series2);

            DataTable dtmes = dm.ExecuteDataTable("getExceptionbyMessage4", dateEdit);
            List<string> exMessage = new List<string>();
            foreach (DataRow dr in dtmes.Rows)
            {
                if (!exMessage.Contains(dr[2].ToString()))
                    exMessage.Add(dr[2].ToString());
            }

            foreach (string filter in exMessage)
            {
                DataTable dtmessa = dtmes.Select("Message= '" + filter.Replace("'", "''") + "'").CopyToDataTable();
                Series series1 = new Series(filter, ViewType.SideBySideStackedBar);
                chartControl1.Series.Add(series1);
                series1.DataSource = dtmessa;
                series1.ArgumentScaleType = ScaleType.Numerical;
                series1.ArgumentDataMember = "Dk";
                series1.ValueScaleType = ScaleType.Numerical;
                ((StackedBarSeriesView)series1.View).BarWidth = 0.15;
                ((BarSeriesView)series1.View).AxisY = myAxisY;
                series1.ValueDataMembers.AddRange(new string[] { "HataSayisi" });
                ((SideBySideStackedBarSeriesView)series1.View).AxisY = myAxisY;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DataSet d = dm.ExecuteDataSet("GetExceptionUsrMsg", dtTime);
            DataTable dtex = d.Tables[0];
            DataTable dtexmessage = d.Tables[1];

            DataTable dt2 = dtexmessage;
            DataTable dt = dtex;
            gridView1.GridControl.DataSource = dt2;

            gridView3.GridControl.DataSource = dt;
            gridView1.BestFitColumns();
            gridView3.BestFitColumns();
            Bind(dtTime, dm);
            dtTime = dtTime.AddMinutes(1);
            if (dtTime == date.AddDays(1))
                timer1.Stop();
        }

        private void dateEdit1_EditValueChanged(object sender, EventArgs e)
        {
            dtTime = dateEdit1.DateTime;
            DataSet d = dm.ExecuteDataSet("GetExceptionUsrMsg", dtTime);
            DataTable dtex = d.Tables[0];
            DataTable dtexmessage = d.Tables[1];
            gridView1.GridControl.DataSource = dtexmessage;
            gridView3.GridControl.DataSource = dtex;
            gridView1.BestFitColumns();
            gridView3.BestFitColumns();
            Bind(dateEdit1.DateTime, dm);
            gridView1.FocusedRowHandle = -1;

            if (dateEdit1.DateTime.Date == DateTime.Now.Date)
            {
                timer1.Interval = 60000;
                timer1.Start();
            }
            else
                timer1.Stop();
        }


        private void gridView3_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (e.RowHandle >= 0)
            {
                int x = (int)(View.GetRowCellValue(e.RowHandle, View.Columns["HataSayisi"]));// GetRowCellDisplayText(e.RowHandle, View.Columns["Programda"]);
                if (x > 1)
                {
                    e.Appearance.BackColor = 
                    e.Appearance.BackColor2 = Color.SeaShell;
                }
            }
        }

        private void gridView1_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView View = sender as GridView;
            if (e.RowHandle >= 0)
            {
                int x = (int)(View.GetRowCellValue(e.RowHandle, View.Columns["HataSayisi"]));// GetRowCellDisplayText(e.RowHandle, View.Columns["Programda"]);
                if (x > 1)
                {
                    e.Appearance.BackColor = 
                    e.Appearance.BackColor2 = Color.SeaShell;
                }
            }
        }

        private void chartControl1_CustomDrawSeries(object sender, CustomDrawSeriesEventArgs e)
        {
            if (e.LegendText.Length > 30)
                e.LegendText = ConvertToMultiLineText(e.LegendText, 30);
        }

        public static string ConvertToMultiLineText(string input, int rowLength)
        {
            input = input.Replace(Environment.NewLine, " ");
            string result = string.Empty;
            string line = string.Empty;

            Stack<string> stack1 = new Stack<string>(input.Split(' '));
            var stack = new Stack<string>(stack1);

            while (stack.Count > 0)
            {
                var word = stack.Pop();
                if (word.Length > rowLength)
                {
                    string head = word.Substring(0, rowLength);
                    string tail = word.Substring(rowLength);

                    word = head;
                    stack.Push(tail);
                }

                if (line.Length + word.Length > rowLength)
                {
                    result += line + Environment.NewLine;
                    line = string.Empty;
                }

                line += word + " ";
            }

            result += line + Environment.NewLine;
            return result.ToString();
        }


        public static string CreateAppDataFolder(string folderName)
        {
            return Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), folderName)).FullName;
        }

    }
}
                                              
